﻿using DynamicWebProxy.Resolvers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DynamicWebProxy
{
    public class ProxyHelper
    {
        private static ProxyFactory proxyFactory = new ProxyFactory();

        private static async Task Init()
        {
            proxyFactory.OnGenerateTestHit += OnGenerateTestHit;
            proxyFactory.OnGenerateFailed += OnGenerateFailed;
            proxyFactory.OnGenerateSucceed += OnGenerateSucceed;
            proxyFactory.OnGenerateLoadFailed += OnGenerateLoadFailed;
            proxyFactory.OnGenerateLoadSucceed += OnGenerateLoadSucceed;

            await proxyFactory.GenerateProxyItems();
        }

        public static IWebProxy GeneralProxy(
            TribleStatus supportPost = TribleStatus.None,
            TribleStatus supportHttps = TribleStatus.None,
            TribleStatus highAnonymity = TribleStatus.None,
            string location = null)
        {
            return GeneralProxyAsync(supportPost, supportHttps, highAnonymity, location).Result;
        }

        public static async Task<IWebProxy> GeneralProxyAsync(
            TribleStatus supportPost = TribleStatus.None,
            TribleStatus supportHttps = TribleStatus.None,
            TribleStatus highAnonymity = TribleStatus.None,
            string location = null)
        {
            if (proxyFactory.ProxyItems.Count == 0) await Init();

            var proxy = await proxyFactory.GenerateProxy(supportPost, supportHttps, highAnonymity, location);

            return proxy;
        }

        private static void OnGenerateTestHit(object? sender, EventArgs.GenerateTestEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"[TEST] {e.Source} {e.Uri} {e.Message}");
        }

        private static void OnGenerateFailed(object? sender, EventArgs.GenerateFailedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"[GENT] {e.Source} 获取代理失败{e.Message}");
        }

        private static void OnGenerateSucceed(object? sender, EventArgs.GenerateSucceedEventArgs e)
        {
            if (!e.IsDefault)
                System.Diagnostics.Debug.WriteLine($"[GENT] {e.Source} 获取代理成功 {e.ProxyItem.Uri} {e.ProxyItem.Location}");
            else
                System.Diagnostics.Debug.WriteLine($"[GENT] {e.Source} 没有从代理池中获取到任何可用代理");
        }

        private static void OnGenerateLoadFailed(object? sender, EventArgs.GenerateLoadFailedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"[LOAD] {e.Source} 加载代理列表失败 {e.Message}");
        }

        private static void OnGenerateLoadSucceed(object? sender, EventArgs.GenerateLoadSucceedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine($"[LOAD] {e.Source} 加载代理列表成功 {e.ProxyItems.Count}条");
        }
    }
}